//图片路径转换为canvas
async function imageToCanvas(url) {
    const maxWidth = 1280;

    const img = document.createElement('img');
    img.src = url;
    img.setAttribute('crossOrigin', 'anonymous');
    await new Promise((resolve) => {
        img.onload = resolve;
    })
    
    const canvas = document.createElement('canvas');

    canvas.width = maxWidth;
    canvas.height = img.height * maxWidth / img.width;

    canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
    return canvas;
}

//添加水印图片
async function addWaterMarkImg(canvas, url='') {
    const ratioWidth = canvas.width * .2;
    const ctx = canvas.getContext('2d');

    const padding = 60;

    const img = document.createElement('img');
    img.src = url;
    img.setAttribute('crossOrigin', 'anonymous');
    await new Promise((resolve) => {
        img.onload = resolve;
    })
    
    ctx.drawImage(img, padding, padding, ratioWidth, img.height * ratioWidth / img.width);
    return canvas;
}

//canvas转换为img
function canvasToImg(canvas) {
    const image = new Image();
    image.src = canvas.toDataURL('image/png');
    return image
}

//封装
export async function waterMark(imgUrl, url) {
    const tempCanvas = await imageToCanvas(imgUrl);
    const canvas = await addWaterMarkImg(tempCanvas, url);
    const img = canvasToImg(canvas);
    return img;
}